import PropTypes from 'prop-types'
import React, { memo, useRef, useState } from 'react'
import { ItemWrapper } from './style'
import { Carousel, Rate } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons'
import Indicator from '@/base-ui/indicator';
import classNames from 'classnames';

const SectionItem = memo((props) => {
  const { itemData, itemWidth, itemClick } = props;

  const [currIndex, setCurrIndex] = useState(0);
  const carouselRef = useRef()
  // 图片轮播 控制上一张下一张
  function controlClickHandler(isNext,e) {
    e.stopPropagation(); // 阻止冒泡
    
    let newIndex = isNext ? (currIndex + 1) : (currIndex - 1)
    if (newIndex < 0) newIndex = itemData?.picture_urls.length - 1
    newIndex = itemData?.picture_urls.length === newIndex ? 0 : newIndex;
    setCurrIndex(newIndex)
    isNext ? carouselRef.current.next() : carouselRef.current.prev()
  }
  // 点击跳转详情
  function itemClickHandle (){
    if (itemClick) itemClick(itemData)
  }
  return (
    <ItemWrapper 
      verifycolor={itemData?.verify_info?.text_color || "#39576a"}
      itemWidth={itemWidth ||"25%"}
      onClick={itemClickHandle}
      >
      <div className="inner">
        {!!itemData?.picture_urls?<div className="swiper">
          <div className="control">
            <div className="left" onClick={e => controlClickHandler(false,e)}>
              <LeftOutlined />
            </div>
            <div className="right" onClick={e=>controlClickHandler(true,e)}>
              <RightOutlined />
            </div>
          </div>
          <div className="indicator">
            <Indicator selectIndex={currIndex}>
              {itemData?.picture_urls.map((item, index) => {
                return <div className={classNames('dot', {active: index===currIndex})} key={item}></div>
              })}
            </Indicator>
          </div>
          <Carousel dots={false} ref={carouselRef}>
            {itemData?.picture_urls.map(picurl => {
              return (<div className="img-cover">
                <img key={picurl} src={picurl} alt="" />
              </div>)
            })}
          </Carousel>
        </div>:
          <div className="img-cover">
            <img src={itemData?.picture_url} alt="" />
          </div>
        }

        <div className="desc">
          {itemData?.verify_info?.messages?.join("·")}
        </div>
        <div className='name'>{itemData.name}</div>
        <div className='price'>¥{itemData.price}/晚</div>
        <div className="bottom">
          <Rate className='rate' allowHalf disabled defaultValue={itemData.star_rating??5} />
          <span className='count'>{itemData.reviews_count}</span>
            {
              itemData.bottom_info && <span className='extra'>·{itemData.bottom_info?.content}</span>
            }
        </div>
      </div>
    </ItemWrapper>
  )
})

SectionItem.propTypes = {
  itemData: PropTypes.object,
  itemWidth: PropTypes.string,
  itemClick:PropTypes.func
}

export default SectionItem